package com.hsd.whb.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsd.whb.entity.Manager;
import com.hsd.whb.entity.Recorder;
import com.hsd.whb.repository.ManagerRepository;
import com.hsd.whb.repository.RecorderRepository;
import com.hsd.whb.utils.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


@Component
public class HwbAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ManagerRepository managerRepository;

    @Autowired
    private RecorderRepository recorderRepository;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            Manager manager = managerRepository.findByUsername(authentication.getName());
            manager.setLastseem(new Date());
            manager.setLogincount(manager.getLogincount() + 1);
            managerRepository.save(manager);
        } else {
            Recorder recorder = recorderRepository.findByUsername(authentication.getName());
            recorder.setLastseem(new Date());
            recorder.setLogincount(recorder.getLogincount() + 1);
            recorderRepository.save(recorder);
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(ResultVOUtil.success()));
    }

}
